package cn.com.main;

import cn.com.spring.annotation.Async;
import cn.com.spring.annotation.Component;
import cn.com.spring.annotation.TimeConsumption;
import cn.com.utils.AopUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 异步演示
 *
 * @author LiuGuodong
 * @date 2024/01/26
 */
@Component
@Service
public class AsyncDemo {

    @Value("${db.password}")
    private String dbPassword;

    public static void main(String[] args) throws Exception {
        System.out.println(Thread.currentThread().getName());
        //自己调用
        AsyncDemo asyncDemo = new AsyncDemo();
        asyncDemo.asynchronousMethod(1);
        //获取自己的代理对象
        AsyncDemo asyncProxy = AopUtil.getAsyncProxy(AsyncDemo.class);
        //通过代理对象调用自己的异步方法
        asyncProxy.asynchronousMethod(1);
        asyncProxy.sayHello();
        asyncProxy.sayHello2();
        asyncProxy.sayHello3();
    }

    public void test() {
        System.out.println("密码: " + dbPassword);
    }

    /**
     * 异步方法 调用案例
     *
     * @throws Exception 例外
     */
    @Async
    public void asynchronousMethod(Integer index) throws Exception {
        System.out.println(index + "  ---  " + Thread.currentThread().getName());
    }

    @Async // 使用异步方法
    public void sayHello() {
        System.out.println(Thread.currentThread().getName());
        System.out.println("hello，1");
    }

    @Async("myThreadPool")
    public void sayHello2() {
        System.out.println(Thread.currentThread().getName());
        System.out.println("hello，2");
    }


    @TimeConsumption(TimeUnit.MICROSECONDS)
    public void sayHello3() {
        try {
            Thread.sleep(1321);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("hello，3");
    }
}
